<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {margin: 0;
      padding: 0;
    }
    /* textarea {
      resize: none;
    } */
  </style>
</head>
<body>
  <textarea></textarea>
  <script>
    const area = document.querySelector('textarea');
    const CONTEXT_STYLE = [
      'letter-spacing',
      'line-height',
      'padding-top',
      'padding-bottom',
      'font-family',
      'font-weight',
      'font-size',
      'text-rendering',
      'text-transform',
      'width',
      'text-indent',
      'padding-left',
      'padding-right',
      'border-width',
      'box-sizing',
    ];
    const HIDDEN_STYLE = `
      height:0 !important;
      visibility:hidden !important;
      overflow:hidden !important;
      position:absolute !important;
      z-index:-1000 !important;
      top:0 !important;
      right:0 !important;
    `
    function getElStyle(el) {
      const styles = window.getComputedStyle(el);
      const boxSizing = styles['boxSizing'];
      const paddSize = (
        parseFloat(styles['padding-top']) + 
        parseFloat(styles['padding-bottom'])
      );
      const borderSize = (
        parseFloat(styles['border-top-width']) + 
        parseFloat(styles['border-bottom-width'])
      );
      const copyStyle = CONTEXT_STYLE.map(style => {
        return `${style}: ${styles[style]}`;
      }).join(';') + ';'
      return {boxSizing, paddSize, borderSize, copyStyle}
    }
    function getAreaHeight(target, minRows, maxRows) {
      const hiddenArea = document.createElement('textarea');
      document.body.appendChild(hiddenArea);
      const {boxSizing, paddSize, borderSize, copyStyle} = getElStyle(target);
      hiddenArea.style = copyStyle;
      hiddenArea.style += HIDDEN_STYLE;
      let height = hiddenArea.scrollHeight;
      if (boxSizing === 'border-box') {
        height += borderSize;
      } else if (boxSizing === 'content-box') {
        height -= paddSize;
      }
      hiddenArea.value = '';
      let singleRowHeight = (hiddenArea.scrollHeight - paddSize)/2;
      console.log(singleRowHeight);
      if(minRows) {
        let minHeight = singleRowHeight * minRows;
        if (boxSizing === 'border-box') {
          minHeight += paddingSize + borderSize
        }
        height = Math.max(minHeight, height)
      }
      if (maxRows) {
        let maxHeight = singleRowHeight * maxRows
        if (boxSizing === 'border-box') {
          maxHeight += paddingSize + borderSize
        }
        height = Math.min(maxHeight, height)
      }
      
      return height + 'px'
    }
    console.log(getAreaHeight(area, 4));
    area.style.height = getAreaHeight(area, 4)
  </script>
</body>
</html>